/* 
	* @params userId
	* @oarams status: -2 socket ready error  -1  scoket connected error 0 socket connected 1 socket is 		ready   101 init 
	* @methods init init methods
*/
class UniSocket {
	
	constructor(userId) {
	    this.userId = userId
	}
	
	init() {                            
		uni.connectSocket({
			url: `ws://192.168.124.12:8081/renren-api/connectWebSocket/${this.userId}`,
			data: {},
			success: (res) => {
				console.log(res, 'socket连接成功',)
				this.status = 0
			},
			fail: (err) => {
				console.log(err, 'socket连接失败')
				this.status = -1
			}
		})
		this.listenOpen()
		this.listenError()
		this.listenMessage()
	}
	
	send(msg) {
		uni.sendSocketMessage({
		      data: msg,
			  success: (res) => {
			  	console.log('消息发送成功')
			  },
			  fail: (err) => {
			  	console.log('消息发送失败')
			  }
		});
	}
	
	listenOpen() {
		console.log('开始监听')
		uni.onSocketOpen(function (res) {
		  console.log('WebSocket连接已打开！')
		  this.socketOpen = true
		  this.status = 1
		})
	}
	
	listenError() {
		uni.onSocketError(function (res) {
		  console.log('WebSocket连接打开失败，请检查！');
		  this.socketOpen = false
		  this.status = -2
		})
	}
	
	listenMessage() {
		console.log('监消息')
		uni.onSocketMessage(function (res) {
		  console.log('收到服务器内容：' + res.data);
		});
	}
}


export default UniSocket